package com.wry.netty.handler;

import com.wry.netty.utils.CurrencyUtil;
import com.wry.netty.utils.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.StandardCharsets;

/**
 * <h1> 将服务端Message转成Byte消息的handler <h1>
 *
 * @author wry
 * @since 2023/4/18 15:56
 */
public class MessageEncoder extends MessageToByteEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message message, ByteBuf byteBuf) throws Exception {
        final ByteBuf buffer = ctx.alloc().buffer();
        final String msg = CurrencyUtil.encodeMsg(message);
        buffer.writeBytes(msg.getBytes(StandardCharsets.UTF_8));

        ctx.writeAndFlush(buffer);
    }
}
